using hao_Common.Consul.Services;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace hao_Common.Consul.HostedServices
{
    public class ConsulHostedService : IHostedService
    {
        private readonly IConsulServiceRegistry _consulServiceRegistry;
        private readonly ILogger<ConsulHostedService> _logger;

        public ConsulHostedService(
            IConsulServiceRegistry consulServiceRegistry,
            ILogger<ConsulHostedService> logger)
        {
            _consulServiceRegistry = consulServiceRegistry;
            _logger = logger;
        }

        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting Consul service registration...");
            
            var success = await _consulServiceRegistry.RegisterServiceAsync();
            if (success)
            {
                _logger.LogInformation("Service registered to Consul successfully");
            }
            else
            {
                _logger.LogError("Failed to register service to Consul");
            }
        }

        public async Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Stopping Consul service registration...");
            
            var success = await _consulServiceRegistry.DeregisterServiceAsync();
            if (success)
            {
                _logger.LogInformation("Service deregistered from Consul successfully");
            }
            else
            {
                _logger.LogError("Failed to deregister service from Consul");
            }
        }
    }
}